package com.pactera.madp.cp.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.pactera.madp.cp.api.dto.wxGZH.WxGZHDto;
import com.pactera.madp.cp.api.entity.WorkContactEmployeeEntity;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.wxgzh.KeyWordEntity;
import com.pactera.madp.cp.api.vo.wxgzh.GzhMsgVo;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CbServiceImpl implements ICbService {

    @Autowired
    private IWorkContactService workContactService;
    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;
    @Autowired
    private IWorkMsgService  workMsgService;
    @Autowired
    private IContactService contactService;
    @Autowired
    private WxGzhKeywordService wxGzhKeywordService;
    @Autowired
    private IWorkEmployeeService workEmployeeService;

    /**
     * 自动回复
     * @param dto
     * @return
     */
    @Override
    public GzhMsgVo handCB(WxGZHDto dto) {
        String msgType = dto.getMsgType();
        if (msgType == null) return textReturn(dto);
        switch (msgType) {
            case "music":
                return null;
            default:
                return textReturn(dto);
        }
    }

    @Override
    public String sendService(GzhMsgVo vo) {
        JSON parse = JSONUtil.parse(vo);
        return parse.toString();
    }

    /**
     * 返回处理
     * @param dto
     * @return GzhMsgVo
     */
    private GzhMsgVo textReturn(WxGZHDto dto) {
        List<KeyWordEntity> keywords = wxGzhKeywordService.query().eq("corp_id", CorpContextHolder.getCorpId()).last("and locate(keyword, \"" + dto.getContent() + "\")").list();
        if (keywords.size() != 0) {
            StringBuffer sb = new StringBuffer("你好，我是小戚戚，希望以下的回答可以满足你：\n");
            int i=1;
            for (KeyWordEntity key:keywords) {
                sb.append(i + "," + key.getReMsg() + "\n");
                i++;
            }
            return new GzhMsgVo("text", sb.toString());
        }
        return isContact(dto);

    }

    /**
     * 是否是企微客户
     * @param dto
     * @return
     */
    private GzhMsgVo isContact(WxGZHDto dto) {
        Integer corpId = CorpContextHolder.getCorpId();
        WorkContactEntity contact = workContactService.getOne(Wrappers.<WorkContactEntity>query().eq("unionid", dto.getUnionId()).eq("corp_id", corpId));
        String qrCode;
        if (contact == null) {
            qrCode = reQR();
            return new GzhMsgVo("qrcode", qrCode);
        } else {
            //是企微客户
            List<Object> employeeIds = workContactEmployeeService.listObjs(Wrappers.<WorkContactEmployeeEntity>query().select("employee_id").eq("contact_id", contact.getId()).eq("status", 1).in("state_inherit", Lists.newArrayList(1, 5)).orderByDesc("create_time"));
            if (employeeIds.size() == 0) {
                qrCode = reQR();
                return new GzhMsgVo("qrcode", qrCode);
            } else {
                List<Object> wxEmployeeIds = workEmployeeService.listObjs(Wrappers.<WorkEmployeeEntity>query().select("wx_user_id").in("id", employeeIds));
                // 查询最近联系人

                String wxEmployeeId = workMsgService.getLatest(contact.getWxExternalUserid(), (ArrayList<Object>) wxEmployeeIds);


                dto.setWxEmployeeId(wxEmployeeId);

                contactService.getGZHMsgToUserByLink(dto);
            }
        }
        return new GzhMsgVo();
    }

    /**
     * 获取随机渠道活码
     * @return
     */
    private String reQR() {
        Integer corpId = CorpContextHolder.getCorpId();
        List<Object> ids = workEmployeeService.listObjs(Wrappers.<WorkEmployeeEntity>lambdaQuery().select(WorkEmployeeEntity::getWxUserId).eq(WorkEmployeeEntity::getStatus, 1).eq(WorkEmployeeEntity::getCorpId, corpId));
        List<String> list = ids.stream().map(m -> m.toString()).collect(Collectors.toList());
        Random random = new Random();
        String wxId = list.get(random.nextInt(list.size()));
        ArrayList<String> reId = new ArrayList<>();
        reId.add(wxId);
        String s = WxApiUtils.requestCreateContactWay(corpId,
                false,
                reId);
        JSONObject obj = JSONUtil.parseObj(s);
        return obj.get("qr_code").toString();
    }


}
